import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:geolocator/geolocator.dart';
import 'package:xiang/utils/http.dart';
import 'package:xiang/utils/permissionHandler.dart';
import 'package:xiang/utils/toast.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String key = '580e2cb36583e5cd4a9ad423a5db7186';
  String baseUrl = 'https://restapi.amap.com/v3';
  String address = '';
  List nearbyCommunities = [];

  @override
  void initState() {
    super.initState();

    permissionHandler.requestLocationPermission();
    permissionHandler.getCurrentLocation().then((position) async {
      await reverseGeocoding(position.latitude, position.longitude);
      await queryNearbyCommunities(position.latitude, position.longitude);
    });
  }

  Future<void> reverseGeocoding(double latitude, double longitude) async {
    String url =
        '$baseUrl/geocode/regeo?key=$key&location=$longitude,$latitude';
    try {
      var response = await http.get(url);
      setState(() {
        address = response['regeocode']['formatted_address'];
      });
      print(address);
    } catch (e) {
      print('查询过程中出现错误: $e');
    }
  }

  Future<void> queryNearbyCommunities(double latitude, double longitude) async {
    String url =
        '$baseUrl/place/around?key=$key&location=$longitude,$latitude&radius=500&types=住宅小区';
    try {
      var response = await http.get(url);
      for (var element in (response['pois'] as List)) {
        // print(element['name']);
        setState(() {
          nearbyCommunities.add(element);
        });
      }
    } catch (e) {
      print('查询过程中出现错误: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('选择社区'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            const Row(
              children: [
                Text(
                  '当前地址',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10),
              child: Row(
                children: [
                  Expanded(child: Text(address)),
                  GestureDetector(
                      onTap: () {
                        permissionHandler
                            .getCurrentLocation()
                            .then((position) async {
                          await reverseGeocoding(
                              position.latitude, position.longitude);
                          await queryNearbyCommunities(
                              position.latitude, position.longitude);
                          // await reverseGeocoding(28.010845, 120.700365);
                          // await queryNearbyCommunities(28.010845, 120.700365);
                        });
                      },
                      child: Row(
                        children: [
                          Icon(Icons.location_searching_outlined,
                              color: Colors.blue),
                          SizedBox(width: 2),
                          Text(
                            '重新定位',
                            style: TextStyle(color: Colors.blue),
                          ),
                        ],
                      ))
                ],
              ),
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '附近社区',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            ListView(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: nearbyCommunities
                    .map((item) => GestureDetector(
                          onTap: () {
                            Navigator.pushNamed(context, '/buildingList',
                                arguments: {'point': item['name']});
                          },
                          child: Container(
                              color: Colors.white,
                              padding: const EdgeInsets.all(10),
                              child: Row(children: [
                                Expanded(child: Text('${item['name']}')),
                                Row(children: [
                                  Icon(Icons.arrow_forward_ios,
                                      size: 16, color: Colors.black),
                                ])
                              ])),
                        ))
                    .toList())
          ],
        ));
  }
}
